package com.example.pool;

import java.util.Random;
import java.util.concurrent.*;

public class CallableAndFuture {
    public static void main(String[] args) throws Exception {
        //Future取得的结果类型和Callable返回的结果类型必须一致，这是通过泛型来实现的。
        //Callable要采用ExecutorSevice的submit方法提交，返回的future对象可以取消任务。
        ExecutorService threadpool = Executors.newSingleThreadExecutor();
        Future<String> future = threadpool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(2000);
                return "hello";
            }
        });

        System.out.println("等待结果");
        System.out.println("拿到结果：" + future.get());

        //先收割成熟的麦子
        //CompletionService用于提交一组Callable任务，其take方法返回已完成的一个Callable任务对应的Future对象。
        //好比我同时种了几块地的麦子，然后就等待收割。收割时，则是那块先成熟了，则先去收割哪块麦子。
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool);
        for (int i = 0; i < 10; i++) {
            final int seq = i;

            completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(new Random().nextInt(5000));
                    return seq;
                }
            });
        }
        for (int i = 0; i < 10; i++) {
            System.out.println(completionService.take().get());
        }
    }
}
